package cn.t.facade.android;


import cn.t.constants.ParamConstants;
import cn.t.core.exception.BizException;
import cn.t.core.mode.PageInfoDTO;
import cn.t.core.mode.PageQueryDTO;
import cn.t.dto.order.ReplenishmentDetailDTO;
import cn.t.dto.order.android.ReplenishmentTotalDTO;
import cn.t.dto.order.repenlement.ReplenishmentPageDTO;
import cn.t.dto.order.repenlement.ReplenishmentQueryRequest;
import cn.t.core.enums.base.CommonError;
import cn.t.enums.device.DeviceTypeEnum;
import cn.t.enums.order.ReplenishmentStatusEnum;
import cn.t.facade.order.ReplenishmentDetailFacade;
import cn.t.facade.order.ReplenishmentFacade;
import cn.t.facade.user.UserSessionFacade;
import cn.t.model.device.CargowayDO;
import cn.t.model.device.DeviceDO;
import cn.t.service.device.CargowayService;
import cn.t.service.device.DeviceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author l
 */
@Slf4j
@Component
@AllArgsConstructor
public class ReplenishmentAndroidFacade {
    @Resource
    private ReplenishmentDetailFacade replenishmentDetailFacade;
    @Resource
    private ReplenishmentFacade replenishmentFacade;
    @Resource
    private UserSessionFacade userSessionFacade;
    @Resource
    private DeviceService deviceService;
    @Resource
    private CargowayService cargowayService;

    public PageInfoDTO<ReplenishmentPageDTO> queryListPage(PageQueryDTO<ReplenishmentQueryRequest> request) {
        ReplenishmentQueryRequest param = request.getParam();
        DeviceDO device = deviceService.getDeviceByImei(param.getImei());
        if (device == null || device.getPin() == null) {
            String errorMessage = String.format("指定的设备不存在 deviceId=%s", param.getImei());
            log.error(errorMessage);
            throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
        }
        param.setDeviceId(device.getId());

        Set<Long> deviceIds = userSessionFacade.getReplenishDeviceIds(device.getFirmId());
        if (ObjectUtils.isEmpty(deviceIds)) {
            return new PageInfoDTO<>(request.getPageNo(), request.getPageSize(), ParamConstants.INT_0, new ArrayList<>());
        }
        param.setDeviceIds(new ArrayList<>(deviceIds));
        if (ReplenishmentStatusEnum.SETTLED.equals(param.getRsStatus())) {
            param.setRsStatus(null);
            param.setStatusList(ReplenishmentStatusEnum.closedList);
        }
        PageInfoDTO<ReplenishmentPageDTO> queryListPage = replenishmentFacade.queryList(request);
        List<ReplenishmentPageDTO> records = queryListPage.getRecords();
        if (ObjectUtils.isEmpty(records)) {
            return queryListPage;
        }


        List<Long> devices = records.stream().map(ReplenishmentPageDTO::getDeviceId).collect(Collectors.toList());
        //查询货道信息
        List<CargowayDO> cargowayList = cargowayService.getCargowayList(devices);
        Map<Long, List<CargowayDO>> carGowayDoMap = cargowayList.stream().collect(Collectors.groupingBy(CargowayDO::getDeviceId));

        List<String> rsSns = records.stream().map(ReplenishmentPageDTO::getRsSn).collect(Collectors.toList());
        Map<String, List<ReplenishmentDetailDTO>> replenishmentDetailMap = replenishmentDetailFacade.getReplenishmentDetailList(rsSns).stream().collect(Collectors.groupingBy(ReplenishmentDetailDTO::getRsSn));

        if (device.getDeviceType().equals(DeviceTypeEnum.ROTATING_CABINET.getCode())) {
            records.forEach(replenishmentPageDTO -> {
                List<CargowayDO> cargowayDoList = carGowayDoMap.get(replenishmentPageDTO.getDeviceId());
                //设置层数
                List<ReplenishmentDetailDTO> replenishmentDetailList =
                        replenishmentDetailMap.get(replenishmentPageDTO.getRsSn()).stream().peek
                                (replenishmentDetailDTO -> replenishmentDetailDTO.setLineNum(cargowayDoList.get(replenishmentDetailDTO.getCargowayNo()).getLineNum()))
                                .collect(Collectors.toList());
                //根据货道层分组
                replenishmentPageDTO.setRotatingDetailMap(replenishmentDetailList.stream().
                        collect(Collectors.groupingBy(ReplenishmentDetailDTO::getLineNum)));
            });

        }else {
            records.forEach(replenishmentPageDTO -> replenishmentPageDTO.setDetails(replenishmentDetailMap.get(replenishmentPageDTO.getRsSn())));

        }
        return queryListPage;
    }

    public ReplenishmentTotalDTO queryCount(ReplenishmentQueryRequest param) {
        DeviceDO device = deviceService.getDeviceByImei(param.getImei());
        if (device == null || device.getPin() == null) {
            String errorMessage = String.format("指定的设备不存在 deviceId=%s", param.getImei());
            log.error(errorMessage);
            throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
        }
        param.setDeviceId(device.getId());

        Set<Long> deviceIds = userSessionFacade.getReplenishDeviceIds(device.getFirmId());
        if (ObjectUtils.isEmpty(deviceIds)) {
            return new ReplenishmentTotalDTO();
        }
        param.setDeviceIds(new ArrayList<>(deviceIds));

        //待补货
        param.setRsStatus(ReplenishmentStatusEnum.PENDING);
        Long pendingNum = replenishmentFacade.getTotal(param);
        //部分完成
        param.setRsStatus(ReplenishmentStatusEnum.PARTIALLY_COMPLETED);
        Long partiallyCompleted = replenishmentFacade.getTotal(param);
        Long settledNum = 0L;
        //补货完成
        param.setRsStatus(null);
        param.setStatusList(ReplenishmentStatusEnum.closedList);
        settledNum = replenishmentFacade.getTotal(param);


        return new ReplenishmentTotalDTO(settledNum, pendingNum, partiallyCompleted);

    }

    /**
     * 小程序端查询补货单汇总信息
     */
    public PageInfoDTO<ReplenishmentPageDTO> queryAppletDataList(@RequestBody PageQueryDTO<ReplenishmentQueryRequest> request) {
        //设备和所属公司必须传一个
        Set<Long> deviceIds = userSessionFacade.getReplenishDeviceIds(null);
        if (ObjectUtils.isEmpty(deviceIds)) {
            return new PageInfoDTO<>(request.getPageNo(), request.getPageSize(), ParamConstants.INT_0, new ArrayList<>());
        }
        ReplenishmentQueryRequest param = request.getParam();
        param.setDeviceIds(new ArrayList<>(deviceIds));
        param.setRsStatus(request.getParam().getStatus());
        return replenishmentFacade.queryList(request);
    }

    public ReplenishmentTotalDTO queryAppletReplenishmentSum() {
        //设备和所属公司必须传一个
        Set<Long> deviceIds = userSessionFacade.getReplenishDeviceIds(null);
        if (ObjectUtils.isEmpty(deviceIds)) {
            return new ReplenishmentTotalDTO();
        }
        ReplenishmentQueryRequest param = new ReplenishmentQueryRequest();
        param.setDeviceIds(new ArrayList<>(deviceIds));

        //待补货
        param.setRsStatus(ReplenishmentStatusEnum.PENDING);
        Long pendingNum = replenishmentFacade.getTotal(param);
        //部分完成
        param.setRsStatus(ReplenishmentStatusEnum.PARTIALLY_COMPLETED);
        Long partiallyCompleted = replenishmentFacade.getTotal(param);
        //补货完成

        param.setRsStatus(null);
        param.setStatusList(ReplenishmentStatusEnum.closedList);
        Long settledNum = replenishmentFacade.getTotal(param);


        return new ReplenishmentTotalDTO(settledNum, pendingNum, partiallyCompleted);

    }
}
